<!--
+----------------------------------------------------------------------
| 友得云客  - 开启房产营销新纪元
+----------------------------------------------------------------------
| Copyright (c) 2019~2023 优得（西安）信息科技有限公司版权所有
+----------------------------------------------------------------------
| Licensed 友得云客不是自由软件 未经允许不可移除相关版权
+----------------------------------------------------------------------
| Author: www.youdeyunke.com
+----------------------------------------------------------------------
-->
<template>
    <div style="display: flex;justify-content: space-between;" v-loading="loading">
        <ai-spider @success="loadData" @close="loadData"  spiderId="POST_ROOMS"  ref="aiSpider" ></ai-spider>

        <div :class="{ 'main-panel': true, full: !currentRoom }">
            <div class="tool-bar">
                <div class="left" style="align-items: center;">
                    楼栋
                    <div class="blank"></div>
                    <el-select size="mini" v-if="postId && buildings.length > 0" v-model="currentBuildingIndex"
                        placeholder="楼栋/单元">
                        <el-option v-for="b, index in buildings" :key="index" :label="b" :value="index">
                        </el-option>
                    </el-select>
                </div>

                <div class="right">
                    <el-button :disabled="!buildings.length" @click="setZptHandle" size="small"
                        icon="el-icon-picture-outline">总平图设置</el-button>
                    <div v-if="showAiSpider" style="margin: 0 10px;">
                        <el-button @click="spiderHandle" @close="loadData" @success="loadData" :disabled="loading" size="small">
                            <i class="icon-ai"></i>
                            AI智能导入
                        </el-button>
                    </div>
                    <el-button :type="buildings.length ? 'danger' : 'info'" :disabled="!buildings.length"
                        @click="deleteAllRoom" size="small" icon="el-icon-delete">一键清空</el-button>
                    <el-button icon="el-icon-plus" @click="showUpload = true" :disabled="import_disable"
                        :title="import_disable ? '该版本无导入功能，请升级到专业版，解锁导入功能' : ''" v-if="!showUpload" type="primary"
                        size="small">批量导入销控表</el-button>
                    <el-button size="small" v-else @click="showUpload = false" icon="el-icon-close">取消</el-button>
                    <el-button type="primary" :disabled="!postId" @click="createHandle" icon="el-icon-plus"
                        size="small">创建房间</el-button>
                </div>


            </div>

            <excel-uploader @success="uploadSuccessHandle" :data="{ post_id: postId }"
                api="/api/admin6/building_rooms/upload" tpl="yifangyijia-tpl-v4.xls" v-if="showUpload"></excel-uploader>

            <div v-else>
                <el-divider></el-divider>

                <div class="status-items">
                    <div class="status-item" v-for="(st, index) in statusItems" :key="index">
                        <i class="dot" :style="{ backgroundColor: st.color }">:</i>
                        <span>{{ st.name }}</span>
                    </div>
                </div>

                <div class="rooms-outer" v-if="currentBuilding">
                    <div class="floor" v-for="(floor, index) in currentBuilding.floors" :key="index">
                        <div class="cell floor-name">{{ floor.floor }}F</div>
                        <div class="rooms">
                            <el-tooltip :class="{ cell: true, active: currentRoom && currentRoom.id === room.id }"
                                :style="{ backgroundColor: room.status.color }" v-for="(room, index) in floor.rooms"
                                :key="index" placement="bottom" effect="light">
                                <div slot="content">
                                    <div class="room-info-cells">
                                        <div class="room-info-cell">
                                            <div class="label">房号</div>
                                            <div class="value">{{ room.name }}</div>
                                        </div>

                                        <div class="room-info-cell">
                                            <div class="label">户型</div>
                                            <div class="value">{{ room.typename }}</div>
                                        </div>
                                        <div class="room-info-cell">
                                            <div class="label">面积</div>
                                            <div class="value">{{ room.area }}</div>
                                        </div>

                                        <div class="room-info-cell">
                                            <div class="label">总价</div>
                                            <div class="value">{{ room.total_price }}</div>
                                        </div>

                                        <div class="room-info-cell">
                                            <div class="label">状态</div>
                                            <div class="value">{{ room.status.name }}</div>
                                        </div>
                                    </div>
                                </div>

                                <div class="room-name" @click="roomClick(room)">
                                    <i class="el-icon-circle-check" style="margin-right:4px;"
                                        v-if="currentRoom && currentRoom.id == room.id"></i>
                                    {{ room.name }}
                                </div>
                            </el-tooltip>
                        </div>
                    </div>
                </div>

                <el-button v-show="selectionRooms.length >= 1" @click="patchDeleteHandle"
                    :disabled="selectionRooms.length == -1" type="danger" size="small" icon="el-icon-delete">删除选中的{{
                    selectionRooms.length }}个房间</el-button>
            </div>
        </div>
        <div class="form-panel" v-if="currentRoom">
            <room-form :types="types" :status-items="statusItems" v-if="currentRoom" @change="roomChange"
                :item="currentRoom"></room-form>
        </div>

    </div>
</template>

<style lang="scss" scoped>
.status-items {
    display: flex;
    margin-bottom: 20px;
    padding: 0 20px;
}

.status-item {
    margin-right: 20px;
}

.status-item .dot {
    width: 14px;
    height: 14px;
    display: inline-block;
    border-radius: 2px;
    margin-right: 4px;
}

.form-panel {
    transition: all 0.3s linear;
    width: 400px;
    padding: 20px;
    border-left: 1px solid #e3e3e3;
}

.main-panel {
    width: calc(100% - 450px);
    transition: all 0.3s linear;
    // padding: 20px;
}

.main-panel.full {
    width: 100%;
}

.app-container {
    display: flex;
    justify-content: space-between;
}

.tool-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.tool-bar .left {
    display: flex;
    justify-content: flex-start;
}

.tool-bar .blank {
    width: 20px;
    display: flex-block;
}

.rooms-outer {
    display: flex;
    flex-direction: column;
    overflow-x: scroll;
}

.floor,
.rooms {
    display: flex;
    justify-content: flex-start;
}

.rooms {
    width: 100%;
}

.cell.floor-name {
    position: sticky;
    left: 0;
    top: 0;
    width: 50px;
    background: #f4f4f4;
    color: #333;
}

.cell {
    box-sizing: border-box;
    height: 40px;
    flex-shrink: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 12px;
    border: 1px solid #fff;
    font-weight: bolder;
    border-radius: 4px;
    font-size: 14px;
}

.room-info-cells {
    display: flex;
    flex-direction: column;
}

.room-info-cell {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
}

.room-info-cell .label {
    font-size: 12px;
    color: #999;
    margin-right: 6px;
}

.room-info-cell .value {
    font-size: 14px;
    color: #000;
}

.rooms .cell {
    width: 100px;
    color: #fff;
    cursor: pointer;
    border-radius: 8px;
}

.rooms .cell.active {
    border-color: blue;
    font-size: 20px;
    color: blue;
    border-width: 5px;
    border-style: dashed;
    background: rgba(0, 0, 0, 0) !important;

}

.room-name {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

.right{
    display: flex;
}
</style>

<script>
import { getLicenseValueByKey } from '@/api/licenseinfo';
import { deleteAllRoomFunc, deleteBuildingRoom, getBuildingRoomList, getBuildingRoomStatus, getTypeList } from "@/api/post";
import ExcelUploader from "@/components//ExcelUploader";
import AiSpider from "@/components/AiSpider/index.vue";
import PostSelector from "@/components/PostSelector";
import RoomForm from "./RoomForm";

export default {
    name: "rooms",
    components: { RoomForm, ExcelUploader, AiSpider, PostSelector },

    data() {
        return {
            showUpload: false,
            showForm: false,
            excelErrorItems: [],
            loading: false,
            selectionRooms: [],
            groupsData: [],
            // postId: null,
            buildings: [],
            types: [],
            statusItems: [],
            currentBuildingIndex: 0,
            currentRoom: null,
            import_disable: true,
        };
    },
    props: {
        postId: {
            type: Number,
            default: null,
        },
        showAiSpider: {
            type: Boolean,
            default: false,
        },
    },

    watch: {
        postId: {
            immediate: true,
            handler(val, oval) {
                if (val) {
                    this.loadData();
                    this.loadTypes()
                }
            },
        },
    },

    mounted: function () {
        this.loadStatus()
        this.loadImportStatus()
    },

    computed: {
        currentBuilding: function () {
            return this.groupsData[this.currentBuildingIndex];
        },
    },

    methods: {
        spiderHandle: function(){
            this.$refs.aiSpider.run({
                post_id: this.postId,
            })
        },
        loadTypes: function () {
            getTypeList(this.postId).then((resp) => {
                this.types = resp.data
            })
        },
        createHandle: function () {
            this.showForm = true
            this.currentRoom = {
                name: '',
                typename: '',
                post_id: this.postId,
                total_price: 0,
                area: 0,
                building: '',
                floor: null,
                status_id: this.statusItems[0].id,
            }
        },
        loadImportStatus() {
            getLicenseValueByKey('BATCH_IMPORT').then((resp) => {
                if (resp.code != 0) {
                    return
                }
                if (resp.data == 'yes') {
                    this.import_disable = false
                }
            })
        },
        deleteAllRoom: function () {
            var params = { building: this.currentBuilding.building, post_id: this.postId }
            var message = ''
            if (this.currentBuilding.building) {
                message = '将永久删除' + this.currentBuilding.building + '楼内所有房间, 是否继续?'
            } else {
                message = '将永久删除该楼内所有房间, 是否继续?'
            }
            this.$confirm(message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteAllRoomFunc(params).then((resp) => {
                    if (resp.status != 0) {
                        return
                    }
                    this.$message({ type: 'success', message: '删除成功!' });
                    this.currentBuildingIndex = 0
                    this.loadData()
                });

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        roomChange: function () {
            this.currentRoom = null
            this.loadData()

        },
        roomClick: function (room) {
            this.currentRoom = room
            console.log('room click', room)
        },

        uploadSuccessHandle: function () {
            this.showUpload = false;
            this.loadData();
        },
        cancleUploadHandle: function () {
            // 关闭批量导入界面
            this.showUpload = false;
            this.excelErrorItems = [];
        },
        roomsSelectionHandle: function (rooms) {
            this.selectionRooms = rooms;
        },

        patchDeleteHandle: function (e) {
            // 批量删除
            this.selectionRooms.forEach((room, i) => {
                deleteBuildingRoom(room.id).then((resp) => {
                    this.$set(room, "delete", true);
                });
            });
        },

        roomsHandle: function (row) {
            // 点击后显示房间列表界面
            this.currentBuildingId = row.id;
        },

        setZptHandle() {
            this.$emit('setZptHandle')
        },

        loadStatus: function () {
            // 状态选项
            var query = { post_id: this.postId }
            getBuildingRoomStatus(query).then((resp) => {
                this.statusItems = resp.data
            })
        },

        loadData: function () {
            var q = { post_id: this.postId };
            this.loading = true;
            var _this = this;
            getBuildingRoomList(q).then((resp) => {
                this.loading = false;
                if (resp.status != 0) {
                    return;
                }
                var rooms = resp.data;
                // 取出buildings
                var buildings = rooms.map((room) => {
                    return room.building;
                });
                // 去重
                buildings = Array.from(new Set(buildings)).sort();
                buildings = buildings.filter((building) => building);
                console.log(buildings, '777');
                // 取出floors
                var floors = rooms.map((room) => {
                    return room.floor;
                });
                // floors = Array.from(new Set(floors)).sort().reverse();
                floors = Array.from(new Set(floors)).sort((a, b) => b - a);
                // 以floor分组
                var groupsData = [];
                buildings.forEach((building) => {
                    var bitem = { building: building, floors: [] };
                    floors.forEach((floor, i) => {
                        var g = { floor: floor, rooms: [] };
                        g.rooms = rooms.filter((r, i) => {
                            return r.floor == floor && r.building === building;
                        });
                        g.rooms = g.rooms.sort((a, b) => {
                            if (a.number < b.number) {
                                return -1;
                            } else {
                                return 1;
                            }
                        });
                        if (g.rooms.length > 0) {
                            bitem.floors.push(g);
                        }
                    });
                    groupsData.push(bitem);
                });

                _this.buildings = buildings;
                _this.groupsData = groupsData;
            });
        },
    },
};
</script>
